// pages/personalDetail/personalDetail.js
import * as echarts from '../../ec-canvas/echarts';
const app = getApp();

var chart;

const ctx = wx.createCanvasContext("bgCanvas2"); //创建一个全局的canvas绘图上下文
const ctx2 = wx.createCanvasContext("runCanvas2");
let mytime = "";
let n = 0;
var w = "";
var h = "";

// 折线图
function initChart(canvas, width, height) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  console.log(width);
  console.log(height);
  canvas.setChart(chart);
  return chart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},

    ifChangePhoneNum: true,

    tempData: {
      hasUserInfo: 1,
      hasWeChatRun: 1,
      hasToken: true,
      canIUse: wx.canIUse('button.open-type.getUserInfo'),
      isUserIn: true,
    },

// 当前页面的用户手机号
    userPhone:"",

    // 用户处理过的手机号
    userHidePhone:"",

    // 当前页面用户信息
    thisPersonInfo:"",

    //计步器
    score: 0,  //传入的进度， 0~100，绘制到此参数处停止。
    ineffectiveDate: '/images/yes_no.png',
    effectiveDate: '/images/yes_yes.png',

    todayTime: new Date().getTime(),
    weekData: {
      pjbs: 0,
      tjts: 0,
      pjqdts: 0,
      pjqdl: 0,
      pjyxrts: 0,
      pjyxrl: 0,
      zxObj: {},
    },
    monthData: {
      pjbs: 0,
      tjts: 0,
      pjqdts: 0,
      pjqdl: 0,
      pjyxrts: 0,
      pjyxrl: 0,
      zxObj: {},
    },

    //折线图选项卡
    lineNavbar: ['近一周', '近一月'],
    lineCurrentTab: 0,
    ec: {
      onInit: initChart
    },

    //日历
    days_style: [
      { month: 'current', day: new Date().getDate(), color: 'white', background: '#000000' },
      { month: 'current', day: new Date().getDate(), color: 'white', background: '#000000' },
      { month: 'current', day: 3, color: '#40B7E6' }
    ]
  },

  run(e) {
    console.log("进入了run");
    let that = this;
    let src = that.data.src; //每个间隔所需绘制的弧度
    let allSrc = that.data.allSrc; //总共需要绘制的弧度
    n++;
    console.log(n+"---"+src+"---"+allSrc);
    let grade = src * (n + 1) > allSrc ? that.data.score : Math.round(src * n / 1.5 * 20000); //百分数
    console.log(grade);
    ctx2.arc(w, h, w - 8, 0.75 * Math.PI, (0.75 + src * n) > 2.25 ? 2.25 * Math.PI : (0.75 + src * n) * Math.PI); //每个间隔绘制的弧度
    ctx2.setStrokeStyle("#52A9FF"); //进度线条颜色
    ctx2.setLineWidth("8");
    ctx2.setLineCap("round");
    ctx2.stroke();
    ctx2.beginPath();
    ctx2.setFontSize(40); //注意不要加引号
    ctx2.setFillStyle("#52A9FF"); //步数颜色
    ctx2.setTextAlign("center");
    ctx2.setTextBaseline("middle");
    ctx2.fillText(grade, w, h);

    ctx2.setFontSize(20); //注意不要加引号
    ctx2.setFillStyle("#52A9FF"); //名次颜色
    ctx2.setTextAlign("center");
    ctx2.setTextBaseline("middle");
    ctx2.fillText('今日', w, h - 50);

    ctx2.draw();

    if (src == 0 || allSrc == 0 || src * n > allSrc) {
      //clearInterval(mytime); //如果绘制完成，停掉计时器，绘制结束
      n = 0;
      return;
    }else{
      setTimeout(function () {
        that.run(e)},1);
    }
  },
  canvasTap() {
    let that = this;
    let allSrc = 0.000075 * that.data.score; //应该绘制的弧度
    console.log("所有的弧度：" + allSrc);
    //计算出每个间隔应该绘制多少弧度。
    let src = allSrc / 40  
    that.setData({
      src: src,
      allSrc: allSrc
    })
    console.log("开始绘制一次");
    that.run();
    //mytime = setInterval(that.run, 1) //5毫秒移动一单位
  },
  lineNavbarTap: function (e) {
    this.setData({
      lineCurrentTab: e.currentTarget.dataset.idx
    });
    this.setZXchart();
  },
  dateChange: function (event) {
    console.log(event.detail);
  },
  prev:function(){
    console.log("上一个月时间");
  },
  next:function(){
    console.log("下一个月时间");
  },
  changePhone: function() {
    this.setData({
      ifChangePhoneNum: false
    })
  },
  dayClick: function (event) {
    let _this = this;
    let clickDay = event.detail.day;
    let changeDay = "days_style[" + 1 + "].day";
    let changeBg = "days_style[" + 1 + "].background";
    _this.reviewThisPage(event.detail);
    this.setData({
      [changeDay]: clickDay,
      [changeBg]: "#E5E5E5"
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;
    console.log(options);
    _this.setData({
      userPhone: options.phone
    });
    
  },

// 该页面初始化完成时的回调函数
  initPageData(){
    let _this = this;
    wx.showLoading({
      title: '正在加载',
    })
    app.getUserInfoFromPhone(_this.data.userPhone,function(_data){
      console.log(_data);
      _this.setData({
        thisPersonInfo: _data,
        userHidePhone: _data.guildUser.user_mobile.substring(0, 3) + "****" + _data.guildUser.user_mobile.substring(7),
        
        score: _data.step ? _data.step.s_step_number:0,
        is_say_yes: _data.sign == 0 ? false : true,
      });

      _this.canvasTap();
      wx.hideLoading();

    });

// 获取用户近一周的数据
    app.getUserStatistics(_this.data.userPhone, new Date(_this.data.todayTime - 6 * 24 * 60 * 60 * 1000), new Date(), function (_data) {
      console.log(_data);
      let pjbs = 0;
      let pjyxrts = 0;
      let dateArray = [];
      let dateStepArray = [];
      _data.user_day_step_num.forEach(function (item, index, array) {
        pjbs += Math.floor(item.step_number);
        dateStepArray.push(Math.floor(item.step_number));
        dateArray.push(item.day.substring(5).replace("-", "/"));
        if (Math.floor(item.step_number) > 10000) {
          pjyxrts++;
        }
      });
      pjbs = Math.ceil(pjbs / _data.user_day_step_num.length);
      _this.setData({
        weekData: {
          pjbs: pjbs,
          tjts: _data.user_day_step_num.length,
          pjqdts: _data.sign_num,
          pjqdl: Math.ceil(_data.sign_num / _data.user_day_step_num.length * 100),
          pjyxrts: pjyxrts,
          pjyxrl: Math.ceil(pjyxrts / _data.user_day_step_num.length * 100),
          zxObj: {
            dateArray: dateArray,
            dateStepArray: dateStepArray
          }
        }
      });
      _this.setZXchart();
    });
    
    // 获取用户近一个月月的数据
    app.getUserStatistics(_this.data.userPhone, new Date(_this.data.todayTime - 30 * 24 * 60 * 60 * 1000), new Date(), function (_data) {
      console.log(_data);

      let pjbs = 0;
      let pjyxrts = 0;
      let dateArray = [];
      let dateStepArray = [];
      _data.user_day_step_num.forEach(function (item, index, array) {
        pjbs += Math.floor(item.step_number);
        dateStepArray.push(Math.floor(item.step_number));
        dateArray.push(item.day.substring(5).replace("-", "/"));
        if (Math.floor(item.step_number) > 10000) {
          pjyxrts++;
        }
      });
      pjbs = Math.ceil(pjbs / _data.user_day_step_num.length);

      _this.setData({
        monthData: {
          pjbs: pjbs,
          tjts: _data.user_day_step_num.length,
          pjqdts: _data.sign_num ,
          pjqdl: Math.ceil(_data.sign_num / _data.user_day_step_num.length * 100),
          pjyxrts: pjyxrts,
          pjyxrl: Math.ceil(pjyxrts / _data.user_day_step_num.length * 100),
          zxObj: {
            dateArray: dateArray,
            dateStepArray: dateStepArray
          }
        }
      });
      _this.setZXchart();
    });

  },

  // 重新初始化数据视图
  reviewThisPage(_dateObj) {
    let _this = this;
    let thisDate = new Date();
    thisDate.setFullYear(_dateObj.year);
    thisDate.setMonth(_dateObj.month - 1);
    thisDate.setDate(_dateObj.day);

    wx.showLoading({
      title: "正在加载",
    });

    // 获取近一周部门统计数据
    app.getDepartmentStatistics(_this.data.departmentId, new Date(thisDate.getTime() - 6 * 24 * 60 * 60 * 1000), thisDate, function (_data) {
      console.log(_data);
      wx.hideLoading();
      let pjbs = 0;
      let pjyxrts = 0;
      let dateArray = [];
      let dateStepArray = [];
      _data.department_day_step_num.forEach(function (item, index, array) {
        pjbs += Math.floor(item.step_number);
        dateStepArray.push(Math.floor(item.step_number));
        dateArray.push(item.day.substring(5).replace("-", "/"));
        if (Math.floor(item.step_number) > 10000) {
          pjyxrts++;
        }
      });
      pjbs = Math.ceil(pjbs / _data.department_day_step_num.length);
      _this.setData({
        weekData: {
          pjbs: pjbs,
          tjts: _data.department_day_step_num.length,
          pjqdts: Math.ceil(_data.sign_num / _data.department_num),
          pjqdl: Math.ceil(_data.sign_num / _data.department_num / _data.department_day_step_num.length * 100),
          pjyxrts: pjyxrts,
          pjyxrl: Math.ceil(pjyxrts / _data.department_day_step_num.length * 100),
          zxObj: {
            dateArray: dateArray,
            dateStepArray: dateStepArray
          }
        }
      });
      _this.setZXchart();
      wx.hideLoading();
    });

    // 获取近一月部门统计数据
    app.getDepartmentStatistics(_this.data.departmentId, new Date(thisDate.getTime() - 30 * 24 * 60 * 60 * 1000), thisDate, function (_data) {
      console.log(_data);
      let pjbs = 0;
      let pjyxrts = 0;
      let dateArray = [];
      let dateStepArray = [];
      _data.department_day_step_num.forEach(function (item, index, array) {
        pjbs += Math.floor(item.step_number);
        dateStepArray.push(Math.floor(item.step_number));
        dateArray.push(item.day.substring(5).replace("-", "/"));
        if (Math.floor(item.step_number) > 10000) {
          pjyxrts++;
        }
      });
      pjbs = Math.ceil(pjbs / _data.department_day_step_num.length);

      _this.setData({
        monthData: {
          pjbs: pjbs,
          tjts: _data.department_day_step_num.length,
          pjqdts: Math.ceil(_data.sign_num / _data.department_num),
          pjqdl: Math.ceil(_data.sign_num / _data.department_num / _data.department_day_step_num.length * 100),
          pjyxrts: pjyxrts,
          pjyxrl: Math.ceil(pjyxrts / _data.department_day_step_num.length * 100),
          zxObj: {
            dateArray: dateArray,
            dateStepArray: dateStepArray
          }
        }
      });
      _this.setZXchart();
      wx.hideLoading();
    });

  },

  setZXchart() {
    let _this = this;
    let _obj = _this.data.lineCurrentTab == 0 ? _this.data.weekData.zxObj : _this.data.monthData.zxObj;
    console.log(_obj);
    let j = 0;
    j = _obj.dateArray ? _obj.dateArray.length : 0;
    // let yxrArray = [];
    // for (let i = 0; i < j; i++) {
    //   yxrArray.push(10000);
    // }
    var option = {
      // color: ["#37A2DA", "#67E0E3", "#9FE6B8"],
      legend: {
        data: ['有效日步数', '当日步数'],
        top: 0,
        left: 'center',
        z: 100,
        textStyle: {
          fontSize: 16
        }
      },
      grid: {
        left: 60,
        right: 20
        // containLabel: true
      },
      tooltip: {
        show: true,
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        // data: ['01/28', '01/29', '01/30', '01/31', '02/01', '02/02', '02/03'],
        data: _obj.dateArray
        // show: false
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        },
        scale: true,
        // show: false
      },
      series: [ {
        name: '每日步数',
        type: 'line',
        data: _obj.dateStepArray
        // data: [8674, 9201, 12672, 14895, 7835, 16921, 16750]
      }]
    };
    if (chart && option) {
      chart.setOption(option);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.createSelectorQuery().select('#canvas-one').boundingClientRect(function (rect) {//监听canvas的宽高
      console.log(rect);
      w = parseInt(rect.width / 2);
      //获取canvas宽的的一半
      h = parseInt(rect.height / 2);
      //获取canvas高的一半，
      //获取宽高的一半是为了便于找到中心点

      ctx.arc(w, h, w - 8, 0.75 * Math.PI, 2.25 * Math.PI); //绘制圆形弧线
      ctx.setStrokeStyle("#dddddd"); //设置填充线条颜色
      ctx.setLineWidth("8");     //设置线条宽度
      ctx.setLineCap("round");        //设置线条端点样式
      ctx.stroke();     //对路径进行描边，也就是绘制线条

      ctx.draw();       //开始绘制
    }).exec()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.commonOnLoad(this);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})